<?php
declare (strict_types = 1);

namespace app\api\exception;

use app\api\service\StatusCode;
use Throwable;
use think\facade\Log;
use think\Response;
use think\exception\Handle;
use think\exception\ValidateException;
use think\facade\Env;

class ExceptionHandle extends Handle
{
    private $code;
    private $msg;

    public function render($request, Throwable $e): Response
    {
        if ($e instanceof \Exception)
        {
            if( $e instanceof ValidateException ){
                $this->code = StatusCode::BAD_REQUEST;
            }else{
                $this->code = $e->getCode();
            }
            $this->msg = $e->getMessage();
        }else{
            if (Env::get('app_debug')){
                return parent::render($request, $e);
            }else{
                $this->code = StatusCode::SERVER_ERROR;
                $this->msg = '服务器内部错误，艾特聂哥！！！';
                Log::write($e->getMessage(),'error');
            }
        }

        $result = [
            'code'        => $this->code,
            'message'     => $this->msg,
            'request_url' => $request->url()
        ];
        return json($result, 200);
    }
}